<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="名称">
              <a-input v-model:value.trim="warehouseWhere.name" placeholder="请输入名称,编码" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="warehouseReload">查询</a-button>
                <a-button @click="warehouseReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="warehouseTableRef" row-key="id" :columns="columns" :datasource="datasource"
        :scroll="{ x: 1000 }" cacheKey="warehouse">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="warehouseOpenEdit()" v-any-permission="['store:warehouse:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="warehouseOpenEdit(record)" v-any-permission="['store:warehouse:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="warehouseRemove(record)">
                <a class="ele-text-danger" v-any-permission="['store:warehouse:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 仓库管理添加、修改弹窗 -->
    <ele-modal :width="460" v-model:visible="warehouseVisible_modal" :confirm-loading="loading"
      :title="warehouseIsUpdate ? '修改仓库管理' : '添加仓库管理'" position="center" :body-style="{ paddingBottom: '8px' }"
      @ok="warehouseSave" :maskClosable="false">
      <a-form ref="warehouseFormRef" :model="warehouseForm" :rules="warehouseRules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="名称" name="name">
          <a-input allow-clear :maxlength="200" placeholder="请输入名称" v-model:value="warehouseForm.name"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="编码" name="code">
          <a-input allow-clear :maxlength="200" placeholder="请输入编码" v-model:value="warehouseForm.code"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="排序" name="ordernum">
          <a-input allow-clear :maxlength="200" placeholder="请输入排序" v-model:value="warehouseForm.ordernum"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea :rows="4" :maxlength="200" placeholder="请输入备注" v-model:value="warehouseForm.remark" autocomplete="off"/>
        </a-form-item>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';

import { pageWarehouse, removeWarehouse, addWarehouse, updateWarehouse } from '@/api/store/warehouse';

// 表格实例
const warehouseTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (warehouseTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    sorter: true
  },
  {
    title: '编码',
    dataIndex: 'code',
    key: 'code',
    sorter: true
  },
  {
    title: '排序',
    dataIndex: 'ordernum',
    key: 'ordernum',
    sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: warehouseWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  orders.sort = orders.sort=='updateTime'? 'update_time':orders.sort
  orders.sort = orders.sort=='createTime'? 'create_time':orders.sort
  return pageWarehouse({ ...where, ...orders, page, limit });
};

/* 搜索 */
const warehouseReload = () => {
  warehouseTableRef?.value?.reload({ page: 1, where: warehouseWhere });
};
const warehouseReload2 = () => {
  warehouseTableRef?.value?.reload();
};

let warehouseWhere_timeout = 0
watch(() => warehouseWhere, (val) => {
  clearTimeout(warehouseWhere_timeout)
  warehouseWhere_timeout = setTimeout(() => {
    warehouseReload();
  }, TIME_OUT);
},
  { deep: true }
)

/*  重置 */
const warehouseReset = () => {
  resetFields();
  warehouseReload();
};

/* 删除单个 */
const warehouseRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeWarehouse(record.id).then((msg) => {
    hide();
    message.success(msg);
    warehouseReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const warehouseCurrent = ref(null);

// 弹窗是否打开
const warehouseVisible_modal = ref(false);

// 是否是修改
const warehouseIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const warehouseFormRef = ref(null);

// 表单数据
const { form: warehouseForm, resetFields: warehouseResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const warehouseRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});

/* 打开编辑弹窗 */
const warehouseOpenEdit = (record) => {
  warehouseResetFormFields();
  warehouseFormRef.value?.clearValidate();
  warehouseCurrent.value = record ?? {};
  warehouseVisible_modal.value = true;
  Object.assign(warehouseForm, record ?? {});
  warehouseIsUpdate.value = !!record;
};

/* 保存编辑 */
const warehouseSave = () => {
  if (!warehouseFormRef.value) {
    return;
  }
  warehouseFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = warehouseIsUpdate.value ? updateWarehouse : addWarehouse;
    saveOrUpdate(warehouseForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      warehouseVisible_modal.value = false;
      warehouseReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<script>
export default {
  name: 'Warehouse'
};
</script>

